﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using EncuentraloSilverlight.ServiceReference2;
using System.Windows.Browser;
using System.Collections.ObjectModel;

namespace EncuentraloSilverlight.Views
{
    public partial class Home : Page
    {
        public Home()
        {
            InitializeComponent();
            string user = Cookie.GetCookie("EncuentraloUser");
            if (user!=null)
            {
                Service2Client webservice = new Service2Client();

                webservice.FindAllUsersCompleted += (obj, eventarg) =>
                {
                    ObservableCollection<User> users = eventarg.Result;

                    foreach (User u in users)
                    {
                        if (u.Name.Equals(user))
                        {
                            NavigationService.Navigate(new Uri("/Views/User_View.xaml", UriKind.Relative));
                            return;
                        }
                    }
                };

                webservice.FindAllSellersCompleted += (obj, eventarg) =>
                {
                    ObservableCollection<Seller> sellers = eventarg.Result;

                    if (sellers != null)
                    {
                        foreach (Seller s in sellers)
                        {
                            if (s.Name.Equals(user))
                            {
                                NavigationService.Navigate(new Uri("/Views/Seller_View.xaml", UriKind.Relative));
                                return;
                            }

                        }
                    }
                };

                webservice.FindAllUsersAsync();
                webservice.FindAllSellersAsync();

            }
        }

        // crear cuenta
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Registrar.xaml", UriKind.Relative));
        }



        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Service2Client webservice = new Service2Client();
            int contador = 0;
            webservice.FindAllUsersCompleted += (obj, eventarg) =>
            {
                ObservableCollection<User> users = eventarg.Result;

                foreach (User u in users)
                {
                    if (textbox_username.Text.Equals(u.Name.ToString()) && textbox_password.Password.Equals(u.Password.ToString()))
                    {
                        Cookie.SetCookie("EncuentraloUser", u.Name);
                        NavigationService.Navigate(new Uri("/Views/User_View.xaml", UriKind.Relative));
                        return;
                    }
                }
                contador++;
                NotUser(contador);

            };

            webservice.FindAllSellersCompleted += (obj, eventarg) =>
                {
                    ObservableCollection<Seller> sellers = eventarg.Result;

                    if (sellers != null)
                    {
                        foreach (Seller s in sellers)
                        {
                            if (textbox_username.Text.Equals(s.Name.ToString()) && textbox_password.Password.Equals(s.Password.ToString()))
                            {
                                Cookie.SetCookie("EncuentraloUser", s.Name);
                                NavigationService.Navigate(new Uri("/Views/Seller_View.xaml", UriKind.Relative));
                                return;
                              
                            }

                        }
                        contador++;
                        NotUser(contador);
                    }
                };

           webservice.FindAllUsersAsync();
           webservice.FindAllSellersAsync();
        }


        private void NotUser(int contador)
        {
            if (contador == 2)
            {
                MessageBox.Show("El Usuario no existe o la contraseña no es correcta");
                textbox_username.Text = "";
                textbox_password.Password = "";
            }
        }

        private void KeyUp_TextBox_CommonExpressSearch(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Cookie.SetCookie("EncuentraloSearch", TextBox_CommonExpressSearch.Text);
                NavigationService.Navigate(new Uri("/Views/BusquedaExpress.xaml", UriKind.Relative));
            }
            
        }

        private void Click_Button_CommonExpressSearch(object sender, RoutedEventArgs e)
        {
            Cookie.SetCookie("EncuentraloSearch", TextBox_CommonExpressSearch.Text);
            NavigationService.Navigate(new Uri("/Views/BusquedaExpress.xaml", UriKind.Relative));
        }


        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Service2Client webservice = new Service2Client();
            ObservableCollection<Product> products = null;

            webservice.FindAllProductsCompleted += (obj, eventarg) =>
            {
                ObservableCollection<Product> destacados = new ObservableCollection<Product>();
                products = eventarg.Result;
                Random r = new Random();
                foreach (Product p in products)
                {
                    int random = r.Next(1,1000);
                    if (random <= 250)
                    {
                        destacados.Add(p);
                    }
                }

                StackPanel mainstack = new StackPanel() { Orientation = Orientation.Horizontal};
                grid1.Children.Add(mainstack);

                StackPanel firststack = new StackPanel() {Orientation= Orientation.Vertical, HorizontalAlignment= HorizontalAlignment.Left };
                mainstack.Children.Add(firststack);

                StackPanel secondstack = new StackPanel() { Orientation = Orientation.Vertical, HorizontalAlignment= HorizontalAlignment.Right };
                mainstack.Children.Add(secondstack);

                StackPanel thirdstack = new StackPanel() { Orientation = Orientation.Vertical, HorizontalAlignment = HorizontalAlignment.Right };
                mainstack.Children.Add(thirdstack);

                int temp = 0;

                webservice.FindAllSellersCompleted += (objj, eventargg) =>
                    {
                        ObservableCollection<Seller> sellers = eventargg.Result;

                        while(destacados.Count > 6)
                        {
                            for (int i = 6; i < destacados.Count; i++)
                            {
                                if (destacados.Count > i)
                                    destacados.RemoveAt(i);
                            }
                        }

                        foreach (Product p in destacados)
                        {
                            StackPanel st = new StackPanel() { Orientation = Orientation.Vertical };
                            Border border = new Border() { BorderThickness = new Thickness(4), BorderBrush = new SolidColorBrush(Colors.Blue) { Opacity = 0.2 }, Margin = new Thickness(15) };
                            border.Child = st;

                            Seller mainseller=null;

                            foreach (Seller sell in sellers)
                            {
                                if (p.SellerID == sell.SellerID)
                                    mainseller = sell;
                            }

                            Label lab1 = new Label() { Content = "Nombre: " + p.Name, Margin = new Thickness(7), MinWidth = 200 };
                            st.Children.Add(lab1);
                            if (mainseller != null)
                            {
                                Label lab2 = new Label() { Content = "Vendedor: " + mainseller.Name, Margin = new Thickness(7), MinWidth = 200 };
                                st.Children.Add(lab2);
                            }
                            TextBox desc = new TextBox() { Text = p.Description, BorderBrush = new SolidColorBrush(Colors.Green), Background = new SolidColorBrush(Colors.LightGray), Opacity = 0.7, BorderThickness = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Stretch, TextWrapping = TextWrapping.Wrap, MaxWidth = 200, Margin = new Thickness(0, 7, 0, 7), TextAlignment = TextAlignment.Center, IsReadOnly = true };
                            st.Children.Add(desc);
                            TextBox pri = new TextBox() { Text = "$" + p.Price, FontWeight = FontWeights.ExtraBold, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 7, 0, 7), MaxWidth = 200, BorderThickness = new Thickness(0), FontSize = 20, IsReadOnly = true, Background = new SolidColorBrush(Colors.Transparent) };
                            st.Children.Add(pri);

                            if (temp == 0)
                            {
                                firststack.Children.Add(border);
                                temp++;
                            }
                            else if (temp == 1)
                            {
                                secondstack.Children.Add(border);
                                temp++;
                            }
                            else
                            {
                                thirdstack.Children.Add(border);
                                temp = 0;
                            }

                        }
                    };
                webservice.FindAllSellersAsync();
            };
            webservice.FindAllProductsAsync();
        }

    }
}
